<?php
/**
 * Created by PhpStorm.
 * User: a
 * Date: 2016/6/7
 * Time: 17:31
 */
namespace Admin\Controller\Report;
use Think\Controller;

class LoaninforeportController extends Controller{

    public function loaninfo_report(){
        $month_time=date("Y-m",strtotime("-1 month",time()));
        $search_array['month_time'] = $month_time;
        $this->assign("search_array",$search_array);
        $this->display();
    }
    /**
     * 贷款基本信息报文table
     */
    public function loaninfo_report_main()
    {
        $page=I("post.page","1");
        $rows=I("post.rows","10");
        $month_time=date("Y-m",strtotime("-1 month",time()));
        $month_time = I("post.month_time",$month_time);
        $select_name = I("post.select_name","");
        $report = D("Report");
        $start_time = strtotime($month_time."-01");
        $end_time = strtotime("+1 month",$start_time)-1;
        $report_array = $report->get_loan_info($start_time,$end_time,$select_name,$page,$rows);
        $report_count=$report->get_loan_info_count($start_time,$end_time,$select_name);
        $one_day=24*3600;
        $now_time=strtotime(date("Y-m-d",time()));
        foreach ($report_array as $key => $value) 
        {
            $borrow_id=$value['binfo_borrowid'];
            $cust_id=$value['cust_id'];
            $binfo_state=$value['binfo_state'];
            $period_number_current=$value["period_number"];
            $repay_down=$value["buinfo_repaydown"];
            if($cust_id==''){
                continue;
            }
            $repay_detail=D("RepayDetail");
            $repay_detail_array=$repay_detail->get_repay_detail($borrow_id);//还款订单详情

            $borrow_info=D("Borrowinfo");//查询客户最大分期金额，和分期订单数
            $borrow_info_array=$borrow_info->report_borrow($cust_id);

            $status_count=$borrow_info_array[0]['count'];//客户分期订单数
            $binfo_maxdebt=$borrow_info_array[0]['max_money'];//最大负债额
            $buinfo_overduesum=$borrow_info_array[0]['sum_isoverdue'];//累计逾期
            $opendate=$value['opendate'];
            $remain_period=0;//剩余还款次数
            $buinfo_recentrepay=$opendate;//最近还款时间
            $isoverdue_count=0;//当前逾期期数
            $repay_balance=0;//余额
            $buinfo_repaystatus="";//24月还款状态
            $sixty_principal=0;//30-60逾期本金
            $ninety_principal=0;//60-90天逾期本金
            $onehundred_principal=0;//90-180天逾期本金
            $other_principal=0;//180天以上逾期本金
            $isoverdue_money=0;//逾期总本息和
            $account_status=1;//账户状态 1、正常，2、逾期，3、结清
            $repay_detail_count=count($repay_detail_array);
            $max_end_date=$repay_detail_array[$repay_detail_count-1]['end_date'];
            $differ_month=differ_month($opendate,$max_end_date);
            $remain_period=$differ_month;
            $differ_now_month=differ_month($opendate,$start_time);
            $buinfo_treatmoney=$repay_detail_array[0]['principal']+$repay_detail_array[0]['interest'];
            if($start_time<=$opendate&&$end_time>=$opendate){
                $tips=2;
                $buinfo_repaydown=$opendate;
                $buinfo_repaystatus="*";
            }else {
                $tips=1;
                for ($k = 0; $k <= $differ_now_month; $k++) {
                    $first_day_month=first_day_month($opendate,$k);
                    $final_day_month=final_day_month($opendate,$k);
                    $value2 = $repay_detail_array[0];
                    $repay_date = $value2['repay_date'];
                    $principal = $value2['principal'];
                    $interest = $value2['interest'];
                    $end_date = $value2['end_date'];
                    $isoverdue = $value2['isoverdue'];
                    $period_number = $value2['period_number'];
                    $actual_pricipal=$value2['actual_pricipal'];
//                    if($end_date>$end_time){
//                        break;
//                    }
                    $repay_status = "*";//单月还款状态
                    if($first_day_month<=$end_date&&$end_date<=$final_day_month){
                        array_remove($repay_detail_array,0);
                        if ($repay_date == 0) {//未还款
//                            $repay_balance += $principal;
                        } else {//已还款
                            $remain_period--;
                            $repay_balance += $actual_pricipal;
//                            if($repay_date<($end_date+86400)) {
<<<<<<< HEAD
//                                $buinfo_recentrepay = $repay_date;
=======
                                $buinfo_recentrepay = $repay_date;
>>>>>>> origin/master_wjx8067
//                            }
                            if ($period_number < $period_number_current) {
                                $repay_status = "N";
                            } else if ($period_number == $period_number_current) {
                                if ($binfo_state == 4 && $repay_down == $repay_date) {
                                    $repay_status = "C";
//                                    $account_status = 3;
                                    $remain_period=0;
                                } else {
                                    $repay_status = "N";
                                }
                            }else{
                                $repay_status="N";
                            }
                        }
                        //判断逾期
                        if ($isoverdue != 0) {
                            if ($repay_date == 0) {
                                $isoverdue_count++;
                                $isoverdue_money += $principal + $interest;
                                $account_status=2;
                                $days = ceil(($now_time - strtotime(date("Y-m-d", $end_date))) / $one_day);
                                if($days>1) {
                                    if ($days <= 30) {
                                        $repay_status = "1";
                                    } elseif ($days <= 60) {
                                        $sixty_principal += $principal;
                                        $repay_status = "2";
                                    } elseif ($days <= 90) {
                                        $ninety_principal += $principal;
                                        $repay_status = "3";
                                    } elseif ($days <= 120) {
                                        $onehundred_principal += $principal;
                                        $repay_status = "4";
                                    } elseif ($days <= 150) {
                                        $onehundred_principal += $principal;
                                        $repay_status = "5";
                                    } elseif ($days <= 180) {
                                        $onehundred_principal += $principal;
                                        $repay_status = "6";
                                    } elseif ($days > 180) {
                                        $other_principal += $principal;
                                        $repay_status = "7";
                                    }
                                }
                            } else {
                                $days = ceil((strtotime(date("Y-m-d", $repay_date))-strtotime(date("Y-m-d", $end_date))) / $one_day);
                                if($days>1) {
                                    if ($days <= 30) {
                                        $repay_status = "1";
                                    } elseif ($days <= 60) {
                                        $repay_status = "2";
                                    } elseif ($days <= 90) {
                                        $repay_status = "3";
                                    } elseif ($days <= 120) {
                                        $repay_status = "4";
                                    } elseif ($days <= 150) {
                                        $repay_status = "5";
                                    } elseif ($days <= 180) {
                                        $repay_status = "6";
                                    } elseif ($days > 180) {
                                        $repay_status = "7";
                                    }
                                }
                            }
                        }
                    }else{
                        $remain_period--;
                        $repay_status="*";
                    }
                    $buinfo_repaystatus .= $repay_status;
                    if($repay_date!=0&&$repay_date<($end_date+86400)){
                        $buinfo_recentrepay=$repay_date;
                    }
                }
<<<<<<< HEAD
=======
                $repay_date=$value["repay_date"];
                if($repay_date!=0&&$repay_date<($value["end_date"]+86400)){
                    $buinfo_recentrepay=$repay_date;
                }
>>>>>>> origin/master_wjx8067
                $buinfo_repaydown=$value["end_date"];
            }
//            $repay_count=$value["count_repay"];
            if($status_count>1){
                $tips=1;
            }
//            if($repay_count==1){
//                $buinfo_repaydown=$opendate;
//            }
            $buinfo_classify=1;//五级分类状态  1、正常，2、关注，3、次级，4、可疑，5、损失，9、未知
            if($isoverdue_count==1){
                $buinfo_classify=2;
            }elseif($isoverdue_count==2){
                $buinfo_classify=3;
            }elseif($isoverdue_count==3){
                $buinfo_classify=4;
            }elseif($isoverdue_count>3||$onehundred_principal!=0||$other_principal!=0){
                $buinfo_classify=5;
            }
            //插入处理数据
            $binfo_address = '430100';//发生地点
            $moth_pay=$value["principal"]+$value["interest"];
            $moth_payed=$value["period_recovery"];
            $report_array[$key]["binfo_address"]=$binfo_address;
            $report_array[$key]["binfo_maxdebt"]=round($binfo_maxdebt);
<<<<<<< HEAD
            $report_array[$key]["binfo_repaymonth"]=($remain_period+1)>$differ_month?$differ_month:($remain_period+1);//还款月数
=======
            $report_array[$key]["binfo_repaymonth"]=$differ_month;//还款月数
>>>>>>> origin/master_wjx8067
            $report_array[$key]["binfo_remainmonth"]=($remain_period+1);//剩余还款月数
            $report_array[$key]["buinfo_treattime"]=$value["borrow_loanperiod"]+$value["delay_time"];//协定还款期数
            $report_array[$key]["buinfo_treatmoney"]=round($buinfo_treatmoney);//协定还款额
            if($buinfo_repaydown==0){
                $buinfo_repaydown=math_date($buinfo_recentrepay,$end_time);
            }
            $report_array[$key]["buinfo_repaydown"]=date("Ymd",$buinfo_repaydown);
            $report_array[$key]["buinfo_recentrepay"]=date("Ymd",$buinfo_recentrepay);
            $report_array[$key]["moth_pay"]=round($moth_pay);//本月应还款金额
            $report_array[$key]["moth_payed"]=round($moth_payed);//本月实际还款金额
            $report_array[$key]["repay_balance"]=round($value['borrow_money']-$repay_balance);
            $report_array[$key]["buinfo_repaystatus"]=str_pad($buinfo_repaystatus,24,"/",STR_PAD_LEFT);
            $report_array[$key]["isoverdue_count"]=$isoverdue_count;
            $report_array[$key]["isoverdue_money"]=round($isoverdue_money);
            $report_array[$key]["sixty_principal"]=round($sixty_principal);
            $report_array[$key]["ninety_principal"]=round($ninety_principal);
            $report_array[$key]["onehundred_principal"]=round($onehundred_principal);
            $report_array[$key]["other_principal"]=round($other_principal);
            $report_array[$key]["buinfo_overduesum"]=$buinfo_overduesum;
            $report_array[$key]["tips"]=$tips;
            $report_array[$key]["buinfo_classify"]=$buinfo_classify;
            $report_array[$key]["account_status"]=$account_status;
            $report_array[$key]["buinfo_workststus"]="0";
        }
        $search_array['month_time'] = $month_time;
        $search_array['select_name'] = $select_name;
        $this->assign("search_array",$search_array);
//        $json = json_encode($report_array);
        $result['total']=$report_count;
        $result['rows']=$report_array;
        $json=json_encode($result);
        echo $json;
//        $this->assign('report_json',$json);
//
//        $this->display();
    }

    /**
     * 贷款基本信息报文导出
     */
    public function loaninfo_report_export() 
    {
        $month_time=date("Y-m",strtotime("-1 month",time()));
        $month_time = I("post.month_time",$month_time);
        $select_name = I("post.select_name","");
        $report = D("Report");
        $start_time = strtotime($month_time."-01");
        $end_time = strtotime("+1 month",$start_time)-1;
        $report_array = $report->get_loan_info($start_time,$end_time,$select_name);
        $one_day=24*3600;
        $now_time=strtotime(date("Y-m-d",time()));

        $org_code = C("org_code");

        //  生成txt文件
        $number_array=C("number_array");
        $flowing_water = "";
        for($j = 0; $j < 3; $j++)
        {
            $k = rand(0,36);
            $flowing_water .= $number_array[$k];
        }
        $dir = $org_code.date("Ymd",time()).$flowing_water."1";
        $file_name = $dir.".txt";
        $path = "Public/file/".$file_name;
        $file = fopen($path,"a+");
        $info_type = 'A';// 信息类别----贷款基本信息段
        $loan_contract = 'H';// 信息类别----贷款合同信息段
        $loan_type = '91';// 贷款类型：91代表个人消费贷款
        $currencies = 'CNY';// 币种
        $binfo_repayhz = '03';// 还款频率
        $yuliu = str_pad("", 30, " ", STR_PAD_RIGHT);// 预留字段
        $buinfo_idtype = '0';// 证件类型:0代表身份证
        $binfo_address = '430100';// 发生地点
        $binfo_ensuretype = '4';// 担保方式


        foreach ($report_array as $key => $value)
        {
            $borrow_id=$value['binfo_borrowid'];
            $contract_id=$value['contract_id'];
            $cust_id=$value['cust_id'];
            $binfo_state=$value['binfo_state'];
            $period_number_current=$value["period_number"];
            $repay_down=$value["buinfo_repaydown"];
            if($cust_id==''){
                continue;
            }
            $repay_detail=D("RepayDetail");
            $repay_detail_array=$repay_detail->get_repay_detail($borrow_id);//还款订单详情

            $borrow_info=D("Borrowinfo");//查询客户最大分期金额，和分期订单数
            $borrow_info_array=$borrow_info->report_borrow($cust_id);

            $status_count=$borrow_info_array[0]['count'];//客户分期订单数
            $binfo_maxdebt=$borrow_info_array[0]['max_money'];//最大负债额
            $buinfo_overduesum=$borrow_info_array[0]['sum_isoverdue'];//累计逾期
            $opendate=$value['opendate'];
            $remain_period=0;//剩余还款次数
            $buinfo_recentrepay=$opendate;//最近还款时间
            $isoverdue_count=0;//当前逾期期数
            $repay_balance=0;//余额
            $buinfo_repaystatus="";//24月还款状态
            $sixty_principal=0;//30-60逾期本金
            $ninety_principal=0;//60-90天逾期本金
            $onehundred_principal=0;//90-180天逾期本金
            $other_principal=0;//180天以上逾期本金
            $isoverdue_money=0;//逾期总本息和
            $account_status=1;//账户状态 1、正常，2、逾期，3、结清
            $repay_detail_count=count($repay_detail_array);
            $max_end_date=$repay_detail_array[$repay_detail_count-1]['end_date'];
            $differ_month=differ_month($opendate,$max_end_date);
            $remain_period=$differ_month;
            $differ_now_month=differ_month($opendate,$start_time);
            $buinfo_treatmoney=$repay_detail_array[0]['principal']+$repay_detail_array[0]['interest'];
            if($start_time<=$opendate&&$end_time>=$opendate){
                $tips=2;
                $buinfo_repaydown=$opendate;
                $buinfo_repaystatus="*";
            }else {
                $tips=1;
                for ($k = 0; $k <= $differ_now_month; $k++) {
                    $first_day_month=first_day_month($opendate,$k);
                    $final_day_month=final_day_month($opendate,$k);
                    $value2 = $repay_detail_array[0];
                    $repay_date = $value2['repay_date'];
                    $principal = $value2['principal'];
                    $interest = $value2['interest'];
                    $end_date = $value2['end_date'];
                    $isoverdue = $value2['isoverdue'];
                    $period_number = $value2['period_number'];
                    $actual_pricipal=$value2['actual_pricipal'];
//                    if($end_date>$end_time){
//                        break;
//                    }
                    $repay_status = "*";//单月还款状态

                    if($first_day_month<=$end_date&&$end_date<=$final_day_month){
                        array_remove($repay_detail_array,0);
                        if ($repay_date == 0) {//未还款
//                            $repay_balance += $principal;
                        } else {//已还款
                            $remain_period--;
                            $repay_balance += $actual_pricipal;
//                            if($repay_date<($end_date+86400)) {
<<<<<<< HEAD
//                                $buinfo_recentrepay = $repay_date;
=======
                                $buinfo_recentrepay = $repay_date;
>>>>>>> origin/master_wjx8067
//                            }
                            if ($period_number < $period_number_current) {
                                $repay_status = "N";
                            } else if ($period_number == $period_number_current) {
                                if ($binfo_state == 4 && $repay_down == $repay_date) {
                                    $repay_status = "C";
//                                    $account_status = 3;
                                    $remain_period=0;
                                } else {
                                    $repay_status = "N";
                                }
                            }else{
                                $repay_status="N";
                            }
                        }
                        //判断逾期
                        if ($isoverdue != 0) {
                            if ($repay_date == 0) {
                                $isoverdue_money += $principal + $interest;
                                $isoverdue_count++;
                                $account_status=2;
                                $days = ceil(($now_time - strtotime(date("Y-m-d", $end_date))) / $one_day);
                                if($days>1) {
                                    if ($days <= 30) {
                                        $repay_status = "1";
                                    } elseif ($days <= 60) {
                                        $sixty_principal += $principal;
                                        $repay_status = "2";
                                    } elseif ($days <= 90) {
                                        $ninety_principal += $principal;
                                        $repay_status = "3";
                                    } elseif ($days <= 120) {
                                        $onehundred_principal += $principal;
                                        $repay_status = "4";
                                    } elseif ($days <= 150) {
                                        $onehundred_principal += $principal;
                                        $repay_status = "5";
                                    } elseif ($days <= 180) {
                                        $onehundred_principal += $principal;
                                        $repay_status = "6";
                                    } elseif ($days > 180) {
                                        $other_principal += $principal;
                                        $repay_status = "7";
                                    }
                                }
                            } else {
                                $days = ceil((strtotime(date("Y-m-d", $repay_date))-strtotime(date("Y-m-d", $end_date))) / $one_day);
                                if($days>1) {
                                    if ($days <= 30) {
                                        $repay_status = "1";
                                    } elseif ($days <= 60) {
                                        $repay_status = "2";
                                    } elseif ($days <= 90) {
                                        $repay_status = "3";
                                    } elseif ($days <= 120) {
                                        $repay_status = "4";
                                    } elseif ($days <= 150) {
                                        $repay_status = "5";
                                    } elseif ($days <= 180) {
                                        $repay_status = "6";
                                    } elseif ($days > 180) {
                                        $repay_status = "7";
                                    }
                                }
                            }
                        }
                    }else{
                        $remain_period--;
                        $repay_status="*";
                    }
                    $buinfo_repaystatus .= $repay_status;
                    if($repay_date!=0&&$repay_date<($end_date+86400)){
                        $buinfo_recentrepay=$repay_date;
                    }
                }
<<<<<<< HEAD
=======
                $repay_date=$value["repay_date"];
                if($repay_date!=0&&$repay_date<($value["end_date"]+86400)){
                    $buinfo_recentrepay=$repay_date;
                }
>>>>>>> origin/master_wjx8067
                $buinfo_repaydown=$value["end_date"];
            }
//            $repay_count=$value["count_repay"];
            if($status_count>1){
                $tips=1;
            }
//            if($repay_count==1){
//                $buinfo_repaydown=$opendate;
//            }
            $buinfo_classify=1;//五级分类状态  1、正常，2、关注，3、次级，4、可疑，5、损失，9、未知
            if($isoverdue_count==1){
                $buinfo_classify=2;
            }elseif($isoverdue_count==2){
                $buinfo_classify=3;
            }elseif($isoverdue_count==3){
                $buinfo_classify=4;
            }elseif($isoverdue_count>3||$onehundred_principal!=0||$other_principal!=0){
                $buinfo_classify=5;
            }
            //插入处理数据
            $moth_pay=$value["principal"]+$value["interest"];
            $moth_payed=$value["period_recovery"];
            $remain_period=$remain_period<0?0:$remain_period;
            $borrow_id=str_pad($contract_id,40," ",STR_PAD_RIGHT);//业务号
            $contract_id=str_pad($contract_id,60," ",STR_PAD_RIGHT);//贷款合同号码
            $binfo_opendate=str_pad($value['binfo_opendate'],8,"0",STR_PAD_LEFT);//开户日期
            $buinfo_contractdown=str_pad($value['buinfo_contractdown'],8,"0",STR_PAD_LEFT);//到期日期
            $binfo_grantdegree=str_pad(round($borrow_info_array[0]['max_money']),10,"0",STR_PAD_LEFT);//授信额度
            $binfo_sgrantdegree=str_pad(round($borrow_info_array[0]['max_money']),10,"0",STR_PAD_LEFT);//共享授信额度
            $binfo_maxdebt=str_pad(round($borrow_info_array[0]['max_money']),10,"0",STR_PAD_LEFT);//最大负债额
            $binfo_repaymonth=str_pad($differ_month,3," ",STR_PAD_RIGHT);//还款月数
<<<<<<< HEAD
            $binfo_remainmonth=str_pad(($remain_period+1)>$differ_month?$differ_month:($remain_period+1),3," ",STR_PAD_RIGHT);//剩余还款月数
=======
            $binfo_remainmonth=str_pad(($remain_period+1),3," ",STR_PAD_RIGHT);//剩余还款月数
>>>>>>> origin/master_wjx8067
            $buinfo_treattime=str_pad($value["borrow_loanperiod"]+$value["delay"],3," ",STR_PAD_RIGHT);//协定还款期数
            $buinfo_treatmoney=str_pad(round($buinfo_treatmoney),10,"0",STR_PAD_LEFT);//协定还款额
            if($buinfo_repaydown==0){
                $buinfo_repaydown=math_date($buinfo_recentrepay,$end_time);
            }
            $buinfo_repaydown=str_pad(date("Ymd",$buinfo_repaydown),8,"0",STR_PAD_LEFT);//结算/应还款日期
            $buinfo_recentrepay=str_pad(date("Ymd",$buinfo_recentrepay),8,"0",STR_PAD_LEFT);//最近一次还款日期
            $moth_pay=str_pad(round($moth_pay),10,"0",STR_PAD_LEFT);//本月应还款金额
            $moth_payed=str_pad(round($moth_payed),10,"0",STR_PAD_LEFT);//本月实际还款金额
            $repay_balance=str_pad(round(round($value['borrow_money']-$repay_balance)),10,"0",STR_PAD_LEFT);//余额
            $isoverdue_count=str_pad($isoverdue_count,2,"0",STR_PAD_LEFT);//当前逾期期数
            $isoverdue_money=str_pad(round($isoverdue_money),10,"0",STR_PAD_LEFT);//当前逾期总额
            $sixty_principal=str_pad(round($sixty_principal),10,"0",STR_PAD_LEFT);//逾期31-60天为归还本金
            $ninety_principal=str_pad(round($ninety_principal),10,"0",STR_PAD_LEFT);//逾期61-90天为归还本金
            $onehundred_principal=str_pad(round($onehundred_principal),10,"0",STR_PAD_LEFT);//逾期91-180天为归还本金
            $other_principal=str_pad(round($other_principal),10,"0",STR_PAD_LEFT);//逾期180天以上为归还本金
            $buinfo_overduesum2=str_pad($buinfo_overduesum,3,"0",STR_PAD_LEFT);//累计逾期期数
            $high_isoverdue=str_pad($buinfo_overduesum,2,"0",STR_PAD_LEFT);;//最高逾期期数
            $buinfo_repaystatus=str_pad($buinfo_repaystatus,24,"/",STR_PAD_LEFT);//24月还款状态
            $tips=str_pad($tips,1,"0",STR_PAD_LEFT);//账户拥有者信息提示
            $cust_name=report_switch($value["cust_name"],30);//姓名
            $cust_identity=str_pad($value["cust_identity"],18," ",STR_PAD_RIGHT);//身份证号码
            $borrow_passtime=str_pad($value["borrow_passtime"],8,"0",STR_PAD_LEFT);//合同生效日期
            $borrow_money=str_pad(round($value["borrow_money"]),10,"0",STR_PAD_LEFT);//贷款合同金额
            $file_string=$info_type.$org_code.$loan_type.$contract_id.$borrow_id.$binfo_address.$binfo_opendate.$buinfo_contractdown.$currencies.$binfo_grantdegree.$binfo_sgrantdegree.
                $binfo_maxdebt.$binfo_ensuretype.$binfo_repayhz.$binfo_repaymonth.$binfo_remainmonth.$buinfo_treattime.$buinfo_treatmoney.$buinfo_repaydown.$buinfo_recentrepay.$moth_pay.
                $moth_payed.$repay_balance.$isoverdue_count.$isoverdue_money.$sixty_principal.$ninety_principal.$onehundred_principal.$other_principal.$buinfo_overduesum2.$high_isoverdue.$buinfo_classify.
                $account_status.$buinfo_repaystatus.$tips.$cust_name.$buinfo_idtype.$cust_identity.$yuliu.$loan_contract.$contract_id.$borrow_passtime.$buinfo_contractdown.$currencies.
                $borrow_money."0";
            fwrite($file,$file_string."\r\n");
        }
        $this->ajaxReturn($file_name);
    }


    /**
     * 贷款基本信息报文(线下)table
     */
    public function loaninfo_report_underline() 
    {
        $month_time=date("Y-m",strtotime("-1 month",time()));
        $month_time = I("post.month_time",$month_time);
        $start_time = strtotime($month_time."-01");
        $end_time = strtotime("+1 month",$start_time)-1;
        $select_num = I("post.select_num","");
        $select_name = I("post.select_name","");
        $report = D("Report");
        $report_array = $report->get_loan_info_underline($start_time,$end_time,$select_num,$select_name);
        $json = json_encode($report_array);
        $this->assign('report_json',$json);

        $search_array['month_time'] = $month_time;
        $search_array['select_num'] = $select_num;
        $search_array['select_name'] = $select_name;
        $this->assign("search_array",$search_array);

        if ($_POST && array_key_exists('addData', $_POST) && $_POST['addData']) 
        {
            // $count = count($_POST['addData']);
            $data = $_POST['addData'][0];
            $data['update_time'] = date('Ymd',time());

            $model = D("Loaninforeport");
            if ($data['loaninforeport_contractnum'] == '') 
            {
                // echo "insert";
                $data['start_time'] = date('Ymd',time());
                $num = date('Ym',time()) . '00001';
                $report1 = D("Loaninforeport");
                while ($report1->where('loaninforeport_contractnum='.$num)->select()) 
                {
                    $num ++;
                }
                $data['loaninforeport_contractnum'] = $num;
                $data = array_slice($data,1);
                $model->add($data);
            }
            else
            {
                // echo "update";
                $model->where('loaninforeport_contractnum='.$data['loaninforeport_contractnum'])->save($data);
            }

            // $model = D("Loaninforeport");
            // if ($model->where('loaninforeport_contractnum='.$data['loaninforeport_contractnum'])->select()) 
            // {
            //     // echo "update";
            //     $model->where('loaninforeport_contractnum='.$data['loaninforeport_contractnum'])->save($data);
            // }
            // else
            // {
            //     $data = array_slice($data,1);
            //     // echo "insert";
            //     $model->add($data);
            // }
        }

        if ($_POST && array_key_exists('delData', $_POST) && $_POST['delData']) 
        {
            $data = $_POST['delData'][0];
            $model = D("Loaninforeport");
            $model->delete($data['loaninforeport_id']);
        }

        $this->display();
    }



    /**
     * 贷款基本信息报文(线下)导出
     */
    public function loaninfo_report_export_underline() 
    {
        $month_time=date("Y-m",strtotime("-1 month",time()));
        $month_time = I("post.month_time",$month_time);
        $start_time = $month_time."-01";
        $end_time = date("Y-m-d",strtotime("+1 month",$start_time)-1);
        $select_num = I("post.select_num","");
        $select_name = I("post.select_name","");
        $report = D("Report");
        $report_array = $report->get_loan_info_underline($start_time,$end_time,$select_num,$select_name);
        $count = count($report_array);

        //  获取P2P组织机构代码
        $org_code = C("org_code");

        //  生成txt文件
        $number_array=C("number_array");
        $flowing_water = "";
        for($j = 0; $j < 3; $j++) 
        {
            $k = rand(0,36);
            $flowing_water .= $number_array[$k];
        }
        $dir = $org_code.date("Ymd",time()).$flowing_water."1";
        $file_name = $dir.".txt";
        $path = "Public/file/".$file_name;
        $file = fopen($path,"a+");

        $info_type = 'A';// 信息类别----贷款基本信息段
        $loan_contract = 'H';// 信息类别----贷款合同信息段
        $loan_type = '91';// 贷款类型：91代表个人消费贷款
        $currencies = 'CNY';// 币种
        $binfo_repayhz = '03';// 还款频率
        $yuliu = str_pad("", 30, " ", STR_PAD_RIGHT);// 预留字段
        $buinfo_idtype = '0';// 证件类型:0代表身份证
        $binfo_address = '430100';// 发生地点
        $binfo_ensuretype = '4';// 担保方式

        for($i = 0; $i < $count; $i++) 
        {
            $borrow_id = str_pad($report_array[$i]["loaninforeport_contractnum"], 60, " ", STR_PAD_RIGHT);// 分期编号
            $businessNum = str_pad($report_array[$i]["loaninforeport_contractnum"], 40, " ", STR_PAD_RIGHT);// 业务号
            $binfo_opendate = $report_array[$i]["loaninforeport_opendate"];// 开户日期
            $binfo_expiredate = $report_array[$i]["loaninforeport_enddate"];// 到期日期
            $binfo_grantdegree = str_pad($report_array[$i]["loaninforeport_grantdegree"], 10, "0", STR_PAD_LEFT);// 授信额度
            $binfo_sgrantdegree = str_pad($report_array[$i]["loaninforeport_sgrantdegree"], 10, "0", STR_PAD_LEFT);// 共享授信额度
            $binfo_maxdebt = str_pad($report_array[$i]["loaninforeport_maxdebt"], 10, "0", STR_PAD_LEFT);// 最大负债额
            $binfo_repaymonth = str_pad($report_array[$i]["loaninforeport_repaymonth"], 3, " ", STR_PAD_RIGHT);// 还款月数
            $binfo_remainmonth = str_pad($report_array[$i]["loaninforeport_remainmonth"], 3, " ", STR_PAD_RIGHT);// 剩余还款月数
            $buinfo_treattime = str_pad($report_array[$i]["loaninforeport_treattime"], 3, " ", STR_PAD_RIGHT);// 协定还款期数
            $buinfo_treatmoney = str_pad(round($report_array[$i]["loaninforeport_treatmoney"]), 10, "0", STR_PAD_LEFT);// 协定还款额
            $buinfo_repaydown = $report_array[$i]["loaninforeport_repaydown"];// 借款还清日期
            $buinfo_recentrepay = $report_array[$i]["loaninforeport_recentrepay"];// 最近还清日期
            $moth_pay = str_pad($report_array[$i]['loaninforeport_mothpayshould'], 10, "0", STR_PAD_LEFT);// 本月应还款金额
            $moth_payed = str_pad($report_array[$i]['loaninforeport_mothpayreal'], 10, "0", STR_PAD_LEFT);// 本月实际还款金额
            $balance = str_pad($report_array[$i]['loaninforeport_balance'], 10, "0", STR_PAD_LEFT);// 余额
            $buinfo_overdue = str_pad($report_array[$i]["loaninforeport_overdue"], 2, "0", STR_PAD_LEFT);// 当前逾期期数
            $buinfo_overduemoney = str_pad($report_array[$i]["loaninforeport_overduemoney"], 10, "0", STR_PAD_LEFT);// 当前逾期金额
            $buinfo_overduea = str_pad($report_array[$i]["loaninforeport_overduea"], 10, "0", STR_PAD_LEFT);// 逾期31~60天未归还本金
            $buinfo_overdueb = str_pad($report_array[$i]["loaninforeport_overdueb"], 10, "0", STR_PAD_LEFT);// 逾期61~90天未归还本金
            $buinfo_overduec = str_pad($report_array[$i]["loaninforeport_overduec"], 10, "0", STR_PAD_LEFT);// 逾期91~180天未归还本金
            $buinfo_overdued = str_pad($report_array[$i]["loaninforeport_overdued"], 10, "0", STR_PAD_LEFT);// 逾期180天以上未归还本金
            $buinfo_overduesum = str_pad($report_array[$i]["loaninforeport_overduesum"], 3, "0", STR_PAD_LEFT);// 累计逾期期数
            $buinfo_overduehigh = str_pad($report_array[$i]["loaninforeport_overduehigh"], 2, "0", STR_PAD_LEFT);// 最高逾期期数
            $buinfo_classify = $report_array[$i]["loaninforeport_classify"];// 五级分类状态
            $buinfo_custid = $report_array[$i]["loaninforeport_accounstate"];// 账户状态
            $buinfo_repaystatus = str_pad($report_array[$i]['loaninforeport_repaystatus'], 24, "/", STR_PAD_LEFT);// 24月(账户)还款状态
            $tips = $report_array[$i]['loaninforeport_infotips'];// 账户拥有者信息提示ID获取：1位数
            $buinfo_name = $report_array[$i]["loaninforeport_name"];// 姓名
            if ($buinfo_name == '') 
            {
                continue;
            }
            $buinfo_name = iconv("UTF-8", "gbk//TRANSLIT", $buinfo_name);
            $buinfo_name = str_pad($buinfo_name, 30, " ", STR_PAD_RIGHT);
            $buinfo_idnumber = str_pad($report_array[$i]["loaninforeport_cardnum"], 18, " ", STR_PAD_RIGHT);// 证件号码
            $buinfo_contractwork = $report_array[$i]["loaninforeport_contractwork"];// 合同生效日期
            $buinfo_contractdown = $report_array[$i]["loaninforeport_contractdown"];// 合同终止日期
            $loaninforeport_contractmoney = str_pad($report_array[$i]['loaninforeport_contractmoney'], 10, "0", STR_PAD_LEFT);// 贷款合同金额
            $buinfo_workststus = $report_array[$i]["loaninforeport_workststus"];//  合同有效状态

            $file_string = $info_type . $org_code . $loan_type . $borrow_id . $businessNum . $binfo_address . $binfo_opendate . $binfo_expiredate . $currencies . $binfo_grantdegree . $binfo_sgrantdegree . $binfo_maxdebt . $binfo_ensuretype . $binfo_repayhz . $binfo_repaymonth . $binfo_remainmonth . $buinfo_treattime . $buinfo_treatmoney . $buinfo_repaydown . $buinfo_recentrepay . $moth_pay . $moth_payed . $balance . $buinfo_overdue . $buinfo_overduemoney . $buinfo_overduea . $buinfo_overdueb . $buinfo_overduec . $buinfo_overdued . $buinfo_overduesum . $buinfo_overduehigh . $buinfo_classify . $buinfo_custid . $buinfo_repaystatus . $tips . $buinfo_name . $buinfo_idtype . $buinfo_idnumber . $yuliu . $loan_contract . $borrow_id . $buinfo_contractwork . $buinfo_contractdown . $currencies . $loaninforeport_contractmoney . $buinfo_workststus;

            fwrite($file,$file_string."\r\n");
        }

        $this->ajaxReturn($file_name);
    }


    /**
     * 贷款基本信息新增
     */
    public function loaninfo_report_add() 
    {
        $this->display();
    }
}